<?php

/**
 * 打印对象的相关信息
 */
if (!function_exists('idump')) {
    function idump($var, $echo = true, $label = null, $strict = true)
    {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            } else {
                $output = $label . ' : ' . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo ($output);
            return null;
        } else {
            return $output;
        }
    }
}

/**
 * 清空数组中的空元素
 */
if (!function_exists('arrayTrim')) {
    function arrayTrim($arr)
    {
        return array_filter($arr, create_function('$v', 'return ! empty($v);'));
    }
}

/**
 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
 * @param string $len 长度
 * @param string $type 字串类型
 * @param string $addChars 额外字符
 * @return string
 */
if (!function_exists('randStr')) {
    function randStr($len = 6, $type = 0, $addChars = '')
    {
        $str = '';
        switch ($type) {
            case 1:
                $chars = str_repeat('0123456789', 3);
                break;
            case 2:
                $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 3:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
                break;
            case 4:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 5:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' . $addChars;
                break;
            default: // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
                $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
                break;
        }
        if ($len > 10) {
            //位数过长重复字符串一定次数
            $chars = ($type == 1) ? str_repeat($chars, $len) : str_repeat($chars, 5);
        }
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }
}

/**
 * 10进制转2、8、16、36、62进制
 * @param int $num 要转换的数字
 * @param int $hex 要转换的进制(2,8,16,36,62)
 * @param int $length 字符宽度
 * @return string
 */
if (!function_exists('hexTrans')) {
    function hexTrans($num, $hex = 62, $length = 0)
    {
        if (!in_array($hex, [2, 8, 16, 36, 62])) {
            return strval($num);
        }
        if ($hex == 2) {
            return decbin($num);
        }
        if ($hex == 8) {
            return decoct($num);
        }
        if ($hex == 16) {
            return dechex($num);
        }
        if ($hex == 36) {
            return base_convert($num, 10, 36);
        }

        $str = '';
        while ($num != 0) {
            $n = $num % $hex;
            switch ($hex) {
                case 62:
                    if (($n >= 10) && ($n <= 35)) {
                        $str .= chr($n + 55);
                        break;
                    }
                    if (($n >= 36) && ($n <= 61)) {
                        $str .= chr($n + 61);
                        break;
                    }
                    $str .= $n;
                    break;
            }
            $num = intval($num / $hex);
        }
        return strrev(str_pad($str, $length, '0', STR_PAD_RIGHT));
    }
}

/**
 * 使用另一个字符串填充字符串前缀为指定长度
 */
if (!function_exists('padLeft')) {
    function padLeft($str, $length)
    {
        return str_pad($str, $length, '0', STR_PAD_LEFT);
    }
}

/**
 * 使用另一个字符串填充字符串后缀为指定长度
 */
if (!function_exists('padRight')) {
    function padRight($str, $length)
    {
        return str_pad($str, $length, '0', STR_PAD_RIGHT);
    }
}

/**
 * 获取文件扩展名
 */
if (!function_exists('getFileExt')) {
    function getFileExt($file = '')
    {
        return strtolower(pathinfo($file, PATHINFO_EXTENSION));
    }
}

/**
 * 图片缩略图文件名
 */
if (!function_exists('getThumb')) {
    function getThumb($file = '')
    {
        if (empty($file)) {
            return;
        }
        extract(pathinfo($file));
        return $dirname . '/' . $filename . '_thumb.' . $extension;
    }
}

/**
 * 字符串截取
 */
if (!function_exists('cutStr')) {
    function cutStr($str, $len)
    {
        $str = strip_tags($str);
        for ($i = 0; $i < $len; $i++) {
            $temp_str = substr($str, 0, 1);
            if (ord($temp_str) > 127) {
                $i++;
                if ($i < $len) {
                    $new_str[] = substr($str, 0, 3);
                    $str = substr($str, 3);
                }
            } else {
                $new_str[] = substr($str, 0, 1);
                $str = substr($str, 1);
            }
        }
        return htmlspecialchars(join($new_str), ENT_QUOTES);
    }
}

/**
 * 字符串截取，并附加省略号
 */
if (!function_exists('cutStr2')) {
    function cutStr2($str, $len)
    {
        $len1 = strlen($str);
        $str = strip_tags($str);
        for ($i = 0; $i < $len; $i++) {
            $temp_str = substr($str, 0, 1);
            if (ord($temp_str) > 127) {
                $i++;
                if ($i < $len) {
                    $new_str[] = substr($str, 0, 3);
                    $str = substr($str, 3);
                }
            } else {
                $new_str[] = substr($str, 0, 1);
                $str = substr($str, 1);
            }
        }

        $new_str = join($new_str);
        if (strlen($new_str) < $len1) {
            $new_str .= '…';
        }
        return htmlspecialchars($new_str, ENT_QUOTES);
    }
}

/**
 * 将特殊字符转换为 HTML 实体
 */
if (!function_exists('tt')) {
    function tt($str)
    {
        return htmlspecialchars($str, ENT_QUOTES);
    }
}

/**
 * 获取指定长度的字符串
 */
if (!function_exists('safe')) {
    function safe($str, $length = 100)
    {
        return mb_substr(trim($str), 0, $length, 'utf-8');
    }
}

/**
 * 过滤特殊HTML标签
 */
if (!function_exists('safe2')) {
    function safe2($str)
    {
        return htmlFilter($str);
    }
}

/**
 * 过滤特殊HTML标签
 */
if (!function_exists('htmlFilter')) {
    function htmlFilter($str)
    {
        $search = array("'<script[^>]*?>(.*?)</script>'i",
            "'(javascript|jscript|vbscript|vbs):'i",
            "'<iframe(.*)>.*</iframe>'i",
            "'<frameset(.*)>.*</frameset>'i",
            "'on(load|exit|error|mouse|key|click)'i");
        $replace = array("\\1", "", "", "", "");
        return preg_replace($search, $replace, $str);
    }
}

/**
 * 自动排版
 */
if (!function_exists('formatMatch')) {
    function formatMatch($str)
    {
        $str = strip_tags($str, '<p><br>');
        $search = [
            '/<p[^>]*?>(.*?)<\/p>/i',
            '/<br[^>]*?>/i',
            '/[&nbsp;]*/i',
        ];
        $replace = ["\\1\n\n", "\n\n", ''];
        return preg_replace($search, $replace, $str);
    }
}

/**
 * 在字符串所有新行之前插入 HTML 段落标记
 * @param string $string String to be formatted.
 * @param boolean $line_breaks When true, single-line line-breaks will be converted to HTML break tags.
 * @param boolean $xml When true, an XML self-closing tag will be applied to break tags (<br />).
 * @return string
 */
function nl2p($string, $line_breaks = true, $xml = true)
{
    // Remove existing HTML formatting to avoid double-wrapping things
    $string = str_replace(['<p>', '</p>', '<br>', '<br />'], '', trim($string));
    // It is conceivable that people might still want single line-breaks
    // without breaking into a new paragraph.
    if ($line_breaks == true) {
        return '<p>' . preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br' . ($xml == true ? ' /' : '') . '>'), $string) . '</p>';
    } else {
        return '<p>' . preg_replace("/([\n|\r\n]{1,})/i", "</p>\n<p>", $string) . '</p>';
    }
}

/**
 * 限定数值的取值范围
 */
if (!function_exists('toLimitLng')) {
    function toLimitLng($num, $min = 0, $max = PHP_INT_MAX)
    {
        $num = intval($num);
        $min = intval($min);
        $max = intval($max);
        if ($num < $min) {
            return $min;
        }
        if ($num > $max) {
            return $max;
        }
        return $num;
    }
}

/**
 * 日期时间格式化
 */
if (!function_exists('toDate')) {
    function toDate($time, $format = 'Y-m-d H:i:s')
    {
        if (empty($time)) {
            return '';
        }
        return date($format, $time);
    }
}

/**
 * 以百分数形式显示
 */
if (!function_exists('percent')) {
    function percent($p, $t)
    {
        return sprintf('%.2f%%', $p / $t * 100);
    }
}

/**
 * 使用 socket 提交数据
 */
if (!function_exists('postData')) {
    function postData($host, $port, $page, $data)
    {
        $sock = fsockopen($host, $port, $errno, $errstr, 30);
        if (!$sock) {
            return '';
        }

        fwrite($sock, 'POST ' . ($page ? $page . ' ' : '') . "HTTP/1.0\r\n");
        fwrite($sock, 'Host: ' . $host . "\r\n");
        fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
        fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
        fwrite($sock, "Accept: */*\r\n");
        fwrite($sock, "\r\n");
        fwrite($sock, $data);
        $headers = '';
        while ($str = trim(fgets($sock, 4096))) {
            $headers .= $str . "\n";
        }

        $body = '';
        while (!feof($sock)) {
            $body .= fgets($sock, 4096);
        }

        fclose($sock);
        return $body;
    }
}

/**
 * 使用 curl 获取数据
 */
if (!function_exists('curlGetData')) {
    function curlGetData($url = '', $header = [])
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            return curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
}

/**
 * 使用 curl 提交数据
 */
if (!function_exists('curlPost')) {
    function curlPost($url, $data = '', $header = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            print curl_error($ch);
        } else {
            curl_close($ch);
            return $result;
        }
    }
}

/**
 * 文件大小格式化
 */
if (!function_exists('filesizeFormat')) {
    function filesizeFormat($size)
    {
        $units = [' B', ' KB', ' MB', ' GB', ' TB'];
        for ($i = 0; $size >= 1024 && $i < 4; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $units[$i];
    }
}

/**
 * 时间长度格式化
 */
if (!function_exists('timelongFormat')) {
    function timelongFormat($seconds)
    {
        return gmstrftime('%H:%M:%S', $seconds);
    }
}

/**
 * 判断是否手机号
 */
if (!function_exists('isMobile')) {
    function isMobile($str)
    {
        if (strlen($str) != 11 || !preg_match('/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/', $str)) {
            return false;
        }
        return true;
    }
}

/**
 * 判断是否邮箱
 */
if (!function_exists('isEmail')) {
    function isEmail($email)
    {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return true;
        }
        return false;
    }
}

/*
 * 验证IP址址
 */
if (!function_exists('isIp')) {
    function isIp($ip)
    {
        $str = trim($ip);
        if (empty($str)) {
            return false;
        }

        $match = '/^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/';
        return preg_match($match, $str);
    }
}

/**
 * 判断是否身份证号
 */
if (!function_exists('isCardid')) {
    function isCardid($vStr)
    {
        $vCity = [
            '11', '12', '13', '14', '15', '21', '22', '23',
            '31', '32', '33', '34', '35', '36', '37',
            '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54',
            '61', '62', '63', '64', '65', '71', '81', '82', '91',
        ];
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) {
            return false;
        }
        if (!in_array(substr($vStr, 0, 2), $vCity)) {
            return false;
        }
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
            return false;
        }
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17; $i >= 0; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
            }
            if ($vSum % 11 != 1) {
                return false;
            }
        }
        return true;
    }
}

/**
 * 汉字字符数统计
 */
if (!function_exists('chineseWordCount')) {
    function chineseWordCount($str = '')
    {
        $reg = '/[\x{4E00}-\x{9FA5}]*/u';
        preg_match_all($reg, $str, $arr);
        return mb_strlen(implode(',', array_map('implode', $arr)), 'utf-8');
    }
}

/**
 * 检测文件编码
 * @param string $file 文件路径
 * @return string|null 返回 编码名 或 null
 */
if (!function_exists('getFileCoding')) {
    function getFileCoding($file)
    {
        $arr = ['UTF-8', 'GBK', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'];
        $str = file_get_contents($file);
        foreach ($arr as $item) {
            $tmp = mb_convert_encoding($str, $item, $item);
            if (md5($tmp) == md5($str)) {
                return $item;
            }
        }
        return null;
    }
}

/**
 * 自动解析编码读到字符串
 * @param string $str 字符串
 * @param string $charset 读取编码
 * @return string 返回读取内容
 */
if (!function_exists('autoReadText')) {
    function autoReadText($str, $charset = 'UTF-8')
    {
        $arr = ['UTF-8', 'GBK', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'];
        foreach ($arr as $item) {
            $tmp = mb_convert_encoding($str, $item, $item);
            if (md5($tmp) == md5($str)) {
                return mb_convert_encoding($str, $charset, $item);
            }
        }
        return $str;
    }
}

/**
 * 根据时间，返回刚刚过去多久
 */
if (!function_exists('justHowLong')) {
    function justHowLong($time)
    {
        $t = time() - $time;
        $f = [
            '31536000' => '年',
            '2592000' => '个月',
            '604800' => '星期',
            '86400' => '天',
            '3600' => '小时',
            '60' => '分钟',
            '1' => '秒',
        ];
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / intval($k))) {
                return $c . $v . '前';
            }
        }
    }
}


if (!function_exists('getNumber')) {
    function getNumber($param){
        $lette = strtoupper(substr($param, 0 , 1));
        $number = strval(substr($param, 1));
        $LetterArr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

        $str = '';
        $newStr = '';

        for ($i = 0; $i < strlen($number) ; $i++) {
            $newStr .='9';
        }
        if (intval($number) / intval($newStr) == 1) {
            $newNumber = '';
            for ($i = 0; $i < strlen($number) ; $i++) {
                $newNumber .='0';
            }
            $newNumber = $newNumber .'1';
            //从A开始
            if ($lette == 'Z') {
                $newNumber =   $LetterArr[0].$newNumber;
            }else{
                $key = array_search($lette, $LetterArr);
                $newNumber =  $LetterArr[ $key + 1].$newNumber;
            }
        }else{
            $len = strlen($number);
            $number = intval($number)+1;
            if ($len - strlen(intval($number))==0) {
                $j = 0;
            }else{
                $j = $len - strlen(intval($number));
            }
            $n = '';
            if ($j > 0) {
                for ($i = 0; $i < $j ; $i++) {
                    $n .='0';
                }
            }
            $newNumber =  $lette.$n.$number;
        }

        return $newNumber;
    }
}

if(!function_exists('uploadImg')){
    function uploadImg($file){
        if ($file->isValid()) {
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = strtolower($file->getClientOriginalExtension());     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            if ($ext === false) {
                return ['code'=>false,'data'=>'无效的图片文件'];
            }
            if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
                return ['code'=>false,'data'=>'无效的图片格式'];
            }

            $target_path = 'upload/box/' . date('Y/md');
            $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
            $targetPath = public_path() . DIRECTORY_SEPARATOR . $target_path;
            if (!is_dir($targetPath)) {
                if (!mkdir($targetPath, 0777, 1)) {
                    return ['code'=>false,'data'=>'无效的图片格式'];
                }
            }
            if($file->move($target_path,$filename)){
                return ['code'=>true,'data'=>$target_path.$filename];
            }else{
                return ['code'=>false,'data'=>'上传失败'];
            }
        }else{
            return ['code'=>false,'data'=>'上传失败'];
        }
    }
}

if(!function_exists('getWeeks')){
    function getWeeks($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i=1; $i<=7; $i++){
            $date[$i] = date($format ,strtotime( '+' . $i-7 .' days', $time));
        }
        return $date;
    }
}

function urlsafe_b64decode($string) {
   $data = str_replace(array('-','_'),array('+','/'),$string);
   $mod4 = strlen($data) % 4;
   if ($mod4) {
       $data .= substr('====', $mod4);
   }
   return base64_decode($data);
 }


 /**
 * 获取指定月份的第一天开始和最后一天结束的时间戳
 *
 * @param int $y 年份 $m 月份
 * @return array(本月开始时间，本月结束时间)
 */
 function mFristAndLast($y = "", $m = ""){
     if ($y == "") $y = date("Y");
     if ($m == "") $m = date("m");
     $m = sprintf("%02d", intval($m));
     $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);

     $m>12 || $m<1 ? $m=1 : $m=$m;
     $firstday = strtotime($y . $m . "01000000");
     $firstdaystr = date("Y-m-01", $firstday);
     $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));

     return array(
         "firstday" => $firstday,
         "lastday" => $lastday
     );
 }
